package exam.driver.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <p>SQLExecute</p>
 * <p>Class thực hiện các câu truy vấn</p>
 * @author PHONGTN
 * @version (17/4/2012)
 */
public class SQLExecute {
	/**
	 * sqlServer:SQLServer
	 */
	private SQLConnection sqlConnection;
	
	/**
	 * preparedStatement:PreparedStatement
	 */
	private PreparedStatement preparedStatement;
	
	/**
	 * Constructor
	 * @param sqlConnection
	 */
	public SQLExecute(SQLConnection sqlConnection) {
		this.sqlConnection = sqlConnection;
	}
	/**
	 * createStatementSql: Tạo truy vấn đến database
	 * @param statement
	 * @throws SQLException 
	 */
	public void createStatementSql(String statement){
		try {
			this.preparedStatement = this.sqlConnection.getConnection().prepareStatement(statement);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * select: thực hiện truy vấn select
	 * @return rsSet
	 * @throws SQLException 
	 */
	public ResultSet select() throws SQLException {
		return this.preparedStatement.executeQuery();
	}
	
	/**
	 * setValue: thưc hiện set giá trị vào truy vấn
	 * @param index
	 * @param value
	 */
	public void setValue(int index, Object value) {
		try {
			this.preparedStatement.setObject(index, value);
		} catch (SQLException e) {
			System.err.println("Error: SQLExecute#setValue(" + index + "," + value + ")");
			e.printStackTrace();
		}
	}
	
	/**
	 * execute: thực thi câu truy vấn insert/update/delete
	 * @return int
	 * @throws SQLException 
	 */
	public int execute() throws SQLException {
		return this.preparedStatement.executeUpdate();
	}
	
	/**
	 * getSQLConnection
	 * @return
	 */
	public SQLConnection getSQLConnection() {
		return this.sqlConnection;
	}
}
